import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

// 每次进入程序，先从本地存储获取购物车信息
var car = JSON.parse(localStorage.getItem('car')) || []
// console.log(car)

export default new Vuex.Store({
  state: {
    // 购物车信息
    car: car,
    // 存储当前购物车商品的 id 集合
    goodsIds: [],
    // 当前购物车商品数据列表
    carGoodsList: []
  },
  mutations: {
    // 刷新当前购物车商品数据
    initCar(state, list) {
      let newlist = []
      list.forEach(item => {
        state.car.forEach(ele => {
          if (item.id + '' === ele.id) {
            item.num = ele.count
            newlist.push(item)
          }
        })
      })
      state.carGoodsList = newlist
    }
  },
  actions: {
    // 每次进入程序，先从本地存储获取商品的 id 集合，再发送 http 请求获取购物车商品数据
    getCarList(context) {
      if (car.length === 0) return
      car.forEach(x => this.state.goodsIds.push(x.id))

      axios
        .get('/api/goods/getshopcarlist/' + this.state.goodsIds.join(','))
        .then(({ data }) => {
          if (data.status !== 0) {
            return this.$toast('服务器异常!')
          }
          context.commit('initCar', data.message)
        })
    },
    // 点击添加到购物车，更新商品 id 集合及本地存储并获取最新购物车商品数据
    addToCar(context, goodInfo) {
      const newId = this.state.goodsIds.find(x => x === goodInfo.id)
      if (newId === undefined) {
        this.state.goodsIds.push(goodInfo.id)
        this.state.car.push(goodInfo)
      } else {
        let index = this.state.car.findIndex(x => x.id === goodInfo.id)
        this.state.car[index].count += goodInfo.count
      }
      localStorage.setItem('car', JSON.stringify(this.state.car))

      axios
        .get('/api/goods/getshopcarlist/' + this.state.goodsIds.join(','))
        .then(({ data }) => {
          if (data.status !== 0) {
            return this.$toast('服务器异常!')
          }
          context.commit('initCar', data.message)
        })
    },
    // 购物车页点击减号减少商品数量
    removeFromCar(context, goodInfo) {
      let index = this.state.car.findIndex(x => x.id === goodInfo.id)
      this.state.car[index].count--
      localStorage.setItem('car', JSON.stringify(this.state.car))
    },
    // 删除商品
    delToCar(context, val) {
      val = val + ''
      let index = this.state.car.findIndex(x => x.id === val)
      this.state.car.splice(index, 1)
      let i = this.state.goodsIds.findIndex(x => x === val)
      this.state.goodsIds.splice(i, 1)
      if (this.state.goodsIds.length !== 0) {
        axios
          .get('/api/goods/getshopcarlist/' + this.state.goodsIds.join(','))
          .then(({ data }) => {
            if (data.status !== 0) {
              return this.$toast('服务器异常!')
            }
            context.commit('initCar', data.message)
          })
      } else {
        this.state.carGoodsList = []
      }
      localStorage.setItem('car', JSON.stringify(this.state.car))
    }
  },
  getters: {
    // 购物车商品总数
    allCount(state) {
      let c = 0
      state.car.forEach(item => {
        c += item.count
      })
      return c
    },
    // 购物车商品总价
    countMoney(state) {
      let m = 0
      state.carGoodsList.forEach(item => {
        m += item.num * item.sell_price
      })
      return m * 100
    }
  }
})
